import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 添加调试信息
console.log('API Base URL:', api.defaults.baseURL);

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    // 添加调试信息
    console.log('API Request:', config.method?.toUpperCase(), config.url);
    return config;
  },
  (error) => {
    console.error('Request Error:', error.message);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 添加详细的错误日志
    console.error('Response Error:', {
      url: error.config?.url,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data
    });
    
    // 处理认证错误
    if (error.response && error.response.status === 401) {
      // 清除本地存储的认证信息
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      
      // 重定向到登录页面
      if (typeof window !== 'undefined') {
        window.location.href = '/auth/login';
      }
    }
    
    return Promise.reject(error);
  }
);

// 认证相关API
export const authAPI = {
  // 用户注册
  register: (userData) => api.post('/auth/register', userData),
  
  // 用户登录
  login: (credentials) => api.post('/auth/login', credentials),
  
  // 用户登出
  logout: () => api.post('/auth/logout'),
  
  // 获取当前用户信息
  getCurrentUser: () => api.get('/auth/me'),
};

// 用户相关API
export const userAPI = {
  // 获取用户列表
  getUsers: (params) => api.get('/users', { params }),
  
  // 获取用户详情
  getUser: (id) => api.get(`/users/${id}`),
  
  // 更新用户信息
  updateUser: (id, userData) => api.put(`/users/${id}`, userData),
  
  // 删除用户
  deleteUser: (id) => api.delete(`/users/${id}`),
};

// 活动相关API
export const activityAPI = {
  // 获取活动列表
  getActivities: (params) => api.get('/activities', { params }),
  
  // 获取活动详情
  getActivity: (id) => api.get(`/activities/${id}`),
  
  // 创建活动
  createActivity: (activityData) => api.post('/activities', activityData),
  
  // 更新活动
  updateActivity: (id, activityData) => api.put(`/activities/${id}`, activityData),
  
  // 删除活动
  deleteActivity: (id) => api.delete(`/activities/${id}`),
};

// 分组相关API
export const groupAPI = {
  // 获取分组列表
  getGroups: (params) => api.get('/groups', { params }),
  
  // 创建分组
  createGroup: (groupData) => api.post('/groups', groupData),
  
  // 更新分组成员
  updateGroupMembers: (id, members) => api.put(`/groups/${id}/members`, { members }),
  
  // 随机分组
  randomGrouping: (groupingData) => api.post('/groups/random', groupingData),
  
  // 删除分组
  deleteGroup: (id) => api.delete(`/groups/${id}`),
};

export default api;